package cc.vicp.djx314.starfood.web;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.HiddenHttpMethodFilter;

/**
 * 改写spring源码实现rest风格delete方法兼容get请求
 * @author 水山清风
 *
 */
public class MyHiddenHttpMethodFilter extends HiddenHttpMethodFilter {
	/**
	 * 默认请求传递rest方法的参数名
	 */
	private String methodParam = DEFAULT_METHOD_PARAM;

	@Override
	public void setMethodParam(String methodParam){
		Assert.hasText(methodParam, "'methodParam' must not be empty");
		this.methodParam = methodParam;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
					throws ServletException, IOException {
		String paramValue = request.getParameter(methodParam);
		String _method = request.getMethod();
		if (StringUtils.hasLength(paramValue)) {
			String method = paramValue.toUpperCase(Locale.ENGLISH);
			/*
			 * delete方法可以用post和get来请求，
			 * 但是put方法必须要用post来请求
			 */
			boolean b = ("GET".equals(_method) && "PUT".equalsIgnoreCase(method)) ||
					("POST".equals(_method) && "PUT".equalsIgnoreCase(method)) ||
					("POST".equals(_method) && "DELETE".equalsIgnoreCase(method)) ||
					("GET".equals(_method) && "DELETE".equalsIgnoreCase(method));
			if(b){
				HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
				filterChain.doFilter(wrapper, response);
			}else{
				filterChain.doFilter(request, response);
			}
		}
		else {
			filterChain.doFilter(request, response);
		}
	}

	/**
	 * 改变请求的方法
	 * @author 水山清风
	 *
	 */
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}
}